package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.IWechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 老人家属Service业务层处理
 * 
 * @author 喜欢吃泡芙
 * @date 2025-10-16
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper,FamilyMember> implements IFamilyMemberService {

    @Autowired
    private IWechatService wechatService;
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private TokenService tokenService;

    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //调用微信接口返回openid
        String openid = wechatService.getOpenid(dto.getCode());
        // 根据openid查询客户信息
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId,openid);
        FamilyMember familyMember = familyMemberMapper.selectOne(queryWrapper);
        //获取手机号
        String phone = wechatService.getPhone(dto.getPhoneCode());
        //判断是否存在
        if(familyMember==null){
            //不存在就创建
            familyMember = new FamilyMember();

            familyMember.setPhone(phone);
            familyMember.setName(DEFAULT_NICKNAME_PREFIX.get(new Random().nextInt(DEFAULT_NICKNAME_PREFIX.size()+1))+phone.substring(7));
            familyMember.setOpenId(openid);
            familyMemberMapper.insert(familyMember);
        }else {
            //用户有没有修改过手机号
            if (StrUtil.equals(familyMember.getPhone(), phone)) {
                familyMember.setPhone(phone);
            }
            familyMemberMapper.updateById(familyMember);
        }
        // 根据用户ID和昵称生成Jwt的token
        Map<String, Object> map = new HashMap();
        map.put("id", familyMember.getId());
        map.put("nickName", familyMember.getName());
        String token = tokenService.createToken(map);
        LoginVo  loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;

    }
    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
}
